package com.ac.exception;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ac.model.LogSystem;
import com.ac.model.LogSystemType;
import com.ac.response.HttpStatus;
import com.ac.response.Res;
import com.ac.util.IPUtils;

import ch.qos.logback.classic.Logger;

/**
 * 校验异常
 */
@Component
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class BindExceptionHandler {

	public static final Logger logger = (Logger) LoggerFactory.getLogger(BindExceptionHandler.class);

	@PostConstruct
	public void init() {
	}

	@ExceptionHandler(BindException.class)
	@ResponseBody
	public Res BindExceptionHandlerFun(HttpServletRequest request,BindException e) {
		String ipAddr = IPUtils.getIpAddr(request);
		String url = ExceptionService.getApiUrl(request);
		Map<String, String> errors = new HashMap<>();
		e.getBindingResult().getAllErrors().forEach((error) -> {
			String fieldName = ((FieldError) error).getField();
			String errorMessage = error.getDefaultMessage();
			errors.put(fieldName, errorMessage);
		});
		LogSystem logSystem = new LogSystem();
		logSystem.setTitle("参数校验异常");
		logSystem.setIp(ipAddr);
		logSystem.setType(LogSystemType.Bind);
		logSystem.setContent(url+"-----"+ExceptionService.exceptionToString(e));
		logSystem.setCode(HttpStatus.ERROR);
		ExceptionService.addLogSystem(logSystem);
		return new Res(HttpStatus.BAD_REQUEST, null, errors);
	}

}
